package com.chenxin.fastdfs.controller;

import com.chenxin.fastdfs.client.FastDfsClient;
import com.chenxin.fastdfs.pojo.FastDfsFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author Administrator
 */
@Controller
public class UploadController {
    private static Logger logger = LoggerFactory.getLogger(UploadController.class);

    @GetMapping("/")
    public String index() {
        return "upload";
    }

    /**
     * @param file
     * @param redirectAttributes
     * @return
     */
    @PostMapping("/upload")
    public String singleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
        String contentType = file.getContentType();
        System.out.println(contentType);
        if (file.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
            return "redirect:upload_status";
        }
        try {
            String path = saveFile(file);
            redirectAttributes.addFlashAttribute("message",
                    "You successfully uploaded '" + file.getOriginalFilename() + "'");
            redirectAttributes.addFlashAttribute("path", "file path url '" + path + "'");
        } catch (Exception e) {
            logger.error("upload file failed", e);
        }
        return "redirect:/uploadStatus";
    }

    @GetMapping("/uploadStatus")
    public String uploadStatus() {
        return "upload_status";
    }


    /**
     * 保存文件
     * 从MultipartFile中读取文件信息，然后使用FastDFSClient将文件上传到FastDFS集群中。
     *
     * @param multipartFile
     * @return
     * @throws IOException
     */
    public String saveFile(MultipartFile multipartFile) throws IOException {
        String[] fileAbsolutePath = {};
        String fileName = multipartFile.getOriginalFilename();
        String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
        byte[] fileBuff = null;
        //获取输入流
        InputStream inputStream = multipartFile.getInputStream();

        int length = 0;
        //网络操作时往往出错调用available()方法时，对发发送的数据可能还没有到达。
        if (inputStream != null) {
            while (length == 0) {
                length = inputStream.available();
            }
            fileBuff = new byte[length];
            inputStream.read(fileBuff);
        }
        inputStream.close();
        FastDfsFile file = new FastDfsFile(fileName, fileBuff, ext);
        try {
            fileAbsolutePath = FastDfsClient.upload(file);  //upload to fastdfs
        } catch (Exception e) {
            logger.error("upload file Exception!", e);
        }
        if (fileAbsolutePath == null) {
            logger.error("upload file failed,please upload again!");
        }
        String path = FastDfsClient.getTrackerUrl() + fileAbsolutePath[0] + "/" + fileAbsolutePath[1];

        logger.info("path = {}", path);
        return path;
    }
}